package cn.jiajunsong.helloservice.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

@RestController
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(){
        return "hello world";
    }

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    public String hello(@RequestParam String name) {
        return "Hello " + name;
    }

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public User hello(@RequestHeader String name, @RequestHeader Integer age) {
        return new User(name, age);
    }

    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    public String hello(@RequestBody User user) {
        return "Hello " + user.getName() + ", " + user.getAge();
    }

    @RequestMapping(value = "/hello4", method = RequestMethod.POST)
    public String hello4(User user) {
        return "Hello " + user.getName() + ", " + user.getAge();
    }

    @RequestMapping(value = "/hello5", method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
    public String hello5() throws Exception {
        int sleepTime = new Random().nextInt(4000);
        Thread.sleep(sleepTime);
        return "hello world";
    }

    @GetMapping("/info")
    public String info() {
        InetAddress inetAddress;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            return "unknown host!";
        }
        return "IP:" + inetAddress.getHostAddress() + " " + "hostName:" + inetAddress.getHostName();
    }

    public String helloFallback() {
        return "error";
    }
}
